<template>
  <div class="login">

    <div class="content">
      <!--      控制跳转密码登录还是手机短信登录login_control为password时是密码登录 login_control为code时为手机短信登录-->
      <h1 class="login_font" @click="turn_password">密码登录</h1>
      <h1 class="login_font" @click="turn_code">手机登录</h1>

      <i @click="close_login" class="el_icon_close">X</i>
      <el-form label-width="100px" class="demo-ruleForm" v-if="login_control==='is_pwd'">

        <el-form-item label="用户名" prop="username">
          <el-input type="username" v-model="username" autocomplete="off" prefix-icon="el-icon-user"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="password" autocomplete="off" prefix-icon="el-icon-key"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="login_password">登录</el-button>
<!--          <el-button @click="resetForm('ruleForm')">重置</el-button>-->
        </el-form-item>
      </el-form>


      <el-form label-width="100px" class="demo-ruleForm" v-if="login_control==='is_code'">

        <el-form-item label="手机号" prop="username">
          <el-input type="username"
                    placeholder="手机号"
                    v-model="mobile"
                    autocomplete="off"
                    prefix-icon="el-icon-phone-outline"
                    @blur="click_mobile"
          ></el-input>
        </el-form-item>

        <el-form-item label="验证码" prop="password">
          <el-input placeholder="验证码"
                    v-model="sms"
                    autocomplete="off"
                    prefix-icon="el-icon-chat-line-round">
            <template slot="append">
              <span class="sms" @click="send_sms">{{ sms_interval }}</span>
            </template>
          </el-input>
        </el-form-item>

        <!--      <el-form-item label="验证码" prop="age">-->
        <!--        <el-input v-model.number="ruleForm.age"></el-input>-->
        <!--      </el-form-item>-->

        <el-form-item>
          <el-button type="primary" @click="login_code">登录</el-button>
<!--          <el-button @click="resetForm('ruleForm')">重置</el-button>-->
        </el-form-item>
      </el-form>
      <div class="foot">
        <span @click="go_register">立即注册</span>
      </div>
    </div>

  </div>
</template>

<script>
export default {
  name: "login",
  data() {
    return {
      username: '',
      password: '',
      mobile: '',
      sms: '',
      login_control: 'is_pwd',
      sms_interval: '发送验证码',
      is_send: false,
    };
  },
  methods: {
    close_login() {
      this.$emit('close');
    },
    go_register() {
      this.$emit('go');
    },
    login_password() {  // 账号密码登录
      if (this.username && this.password) {
        //发送请求
        this.$axios.post(this.$settings.base_url + '/user/login/', {
          username: this.username,
          password: this.password
        }).then(response => {
          //把用户信息保存到cookie中
          this.$cookies.set('token', response.data.token, '7d')
          this.$cookies.set('username', response.data.username, '7d')
          //关闭登录窗口
          this.$emit('close')
          this.$emit('loginsuccess')
        }).catch(error => {
        })
      } else {
        this.$message({
          message: '用户名或密码必须填',
          type: 'warning',
          onClose() { //回调
          }
        });
      }
    },

    login_code(){  // 手机短信登录
      if (this.mobile && this.sms) {
        //发送请求
        this.$axios.post(this.$settings.base_url + '/user/code_login/', {
          mobile: this.mobile,
          code: this.sms
        }).then(response => {
          //把用户信息保存到cookie中
          this.$cookies.set('token', response.data.token, '7d')
          this.$cookies.set('username', response.data.username, '7d')
          //关闭登录窗口
          this.$emit('close')
          this.$emit('loginsuccess')
        }).catch(error => {
        })
      } else {
        this.$message({
          message: '验证码必须填写',
          type: 'warning',
          onClose() { //回调
          }
        });
      }
    },

    turn_code() {
      this.login_control = "is_code"
    },
    turn_password() {
      this.login_control = "is_pwd"
    },

    send_sms() {
      // 如果手机号合法，则可以点击获取验证码按钮，点击后设置一个1秒的定时器不断修改sms_interval，
      // 因为数据驱动页面，所以秒数会不停刷新
      if (!this.is_send) {
        return
      }
      this.is_send = false
      let sms_interval_time = 60;
      this.sms_interval = '发送中...'

      this.$axios.get(this.$settings.base_url + '/user/send/', {params: {'telephone': this.mobile}}).then(response => {
        console.log(this.mobile)
        // 因为后端没有短信服务，这里强行改成成功    this.response.code
        if (1) {
          this.$message({
            message: '发送验证码成功',
            type: 'success',
            duration: 1000,
          })
        }
      }).catch(error => {
      })

      let timer = setInterval(() => {
        if (sms_interval_time <= 1) {
          clearInterval(timer) // 如果小于等于1，把定时器清除
          this.sms_interval = '获取验证码'
          this.is_send = true // 重新恢复点击发送功能
        } else {
          sms_interval_time -= 1
          this.sms_interval = `${sms_interval_time}秒后再发`
        }
      }, 1000)

    },

    click_mobile() {
      if (!this.mobile) {
        return
      }
      if (!this.mobile.match(/^1[3-9][0-9]{9}$/)) {
        this.$message({
          message: '手机号有误',
          type: 'warning',
          duration: 1000,
          onClose: () => {
            this.mobile = ''
          }
        })
        return false
      }
      // 发送axios请求
      this.$axios.get(this.$settings.base_url + '/user/check_telephone/', {params: {telephone: this.mobile}}).then(response => {
        if (response.data.code) {
          //手机号存在，允许发送验证码
          this.is_send = true
        } else {
          this.$message({
            message: '手机号不存在',
            type: 'warning',
            duration: 1000,
            onClose: () => {
              this.mobile = ''
            }
          })
        }
      }).catch(error => {
        console.log(error)
      })

    },

    // 下面两个函数没用的
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert('submit!');
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },


  }
}
</script>

<style scoped>
.login {
  width: 100vw;
  height: 100vw;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 666;
  background-color: rgba(0, 0, 0, 0.3);
}

.el_icon_close {
  font-size: 20px;
  cursor: pointer;
  position: fixed;
  margin-right: 0;
}

.login_font {
  font-size: 20px;
  padding-top: 10px;
  margin-top: 10px;
}

.content {
  background-color: #fafafa;
  width: 500px;
  height: 300px;
  margin-left: calc(50% - 500px / 2);
  margin-top: 100px
}

.demo-ruleForm {
  width: 400px;
  height: 200px;
  padding-top: 30px;
}
</style>
